Skip to content

feat(base): add self-contained Matrix2d storage and math - #8317

Open
kirk0830 wants to merge 16 commits into
deepmodeling:developfrom
kirk0830:pr/08-matrix2d
Open

kirk0830 wants to merge 16 commits into
deepmodeling:developfrom
kirk0830:pr/08-matrix2d

Conversation

@kirk0830

@kirk0830 kirk0830 commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Matrix2d<T> is a small, self-contained value type for representing and
operating on a two-dimensional matrix in ABACUS. It is the rank-two
NDArray<T, 2> specialization: the object owns its local storage and carries
either a host layout or a frozen block-cyclic distributed layout. Global and
local extents, ownership, leading dimension, process-grid coordinates, and the
BLACS/ScaLAPACK context therefore travel with the data instead of being passed
around as separate, easy-to-desynchronize pieces.

The same interface works for host matrices, serial frozen layouts, and active
MPI distributions. Matrix algorithms can take a Matrix2d<T> (or a
non-owning Matrix2dView<T>) without reaching into an LCAO layout object or
reconstructing pointer offsets themselves.

Quick start

Here is the MPI-build flow the API is designed to make routine: build complete
host inputs on every rank, create one distributed layout and scatter the host
values into it, run the linear algebra as collective value-returning
operations, then gather the result as an ordinary host matrix:

#include "source_base/matrix2d.h"
#include "source_base/matrix2d_linalg.h"

Matrix2d<double> example(const int n,
                         const int nrproc,
                         const int ncproc,
                         const int nb)
{
    // The full inputs are replicated on every rank in MPI_COMM_WORLD.
    const Matrix2d<double> identity_host
        = matrix2d_linalg::eye<double>(n);
    const Matrix2d<double> a_host
        = matrix2d_linalg::scale(identity_host, 2.0);

    Matrix2d<double> x_host(n, n);
    x_host.fill(1.0);

    Matrix2d<double> a(n, n, nrproc, ncproc, nb, MPI_COMM_WORLD);
    Matrix2d<double> x(a.distribution());

    a.scatter(a_host);
    x.scatter(x_host);

    // B = A*X and X_solution = A^{-1}*B, without modifying A or B.
    const Matrix2d<double> b = matrix2d_linalg::matmul(a, x);
    const Matrix2d<double> x_solution = matrix2d_linalg::solve(a, b);

    return x_solution.gather();
}

Value-returning calls such as matmul(A, B), solve(A, B), and inv(A)
return a complete Matrix2d<T> by value. They do not mutate their inputs. The
result inherits the relevant host or frozen distributed layout: solve uses
the right-hand-side layout, matmul uses the left-input process grid and BLACS
context, and inv preserves the input layout. On active MPI distributions these
operations remain collective, so every rank calls them in the same order.

The output-parameter forms matmul(A, B, C), solve(A, B, X), and
inv(A, AI) write the same complete result into an existing matrix. Callers
that deliberately need zero-copy mutation can use the separately named
low-level _inplace primitives over Matrix2dView; for example,
solve_inplace(A, B) documents that it overwrites A with its LU factors and
replaces B with the solution. Those primitives are escape hatches, not the
recommended developer-facing entry points.

Every rank supplies the complete a_host and x_host matrices. The
block-cyclic layout is created once when a is constructed; x reuses
a.distribution(), and value-returning results carry their own valid layout
context. scatter() marks the host-to-distributed boundary and gather() marks
the distributed-to-host boundary. A root-only gather_on_root() placeholder is
never fed back into a collective operation.

Problems this API is designed to remove

The existing LCAO two-dimensional matrix code commonly passes a raw buffer
together with a Parallel_Orbitals, a Parallel_2D-style layout, local row and
column counts, a leading dimension, and sometimes a BLACS context. Each caller
must remember which values belong together, which rank owns an entry, whether
the buffer is row-major or column-major, and whether padding is present. That
makes index arithmetic, copying, returning results, and preserving descriptor
context easy to get subtly wrong.

Matrix2d moves those details behind one value:

  • storage ownership and lifetime are attached to the matrix;
  • global and local shapes, the leading dimension, ownership, and process-grid
    state are queryable from the same object;
  • local and global accessors use the layout rather than requiring each caller
    to reconstruct offsets;
  • operations validate compatible shapes and layouts and construct results with
    the required layout context;
  • a borrow is explicit as Matrix2dView, while an owned value is explicit as
    Matrix2d.

This PR does not yet migrate production LCAO call sites. It establishes the
value and interface that would let those call sites stop passing distribution
state implicitly or recomputing offsets. Until such migrations land, the
existing production paths are unchanged.

Compared with raw pointers

A raw T* says nothing about who frees it, how many elements it contains,
whether it is host row-major or distributed column-major, where column padding
starts, or which rank owns a global coordinate. Matrix2d owns its storage,
carries its extents and layout, and provides checked local/global access plus
ownership queries. It is copyable and movable: copies have independent storage,
moves are noexcept, and copies share only the immutable distribution handle.
There is no hidden copy-on-write: copying a matrix copies its values.

The unsafe escape hatch remains available through data() for BLACS, LAPACK,
or existing kernels, but it is now an explicit boundary on an otherwise
self-describing object. local_storage_size() is not assumed to equal
nrloc() * ncloc() because the physical buffer may contain leading-dimension
padding.

Compared with Parallel_Orbitals and Parallel_2D

The legacy Parallel_2D object describes a block-cyclic layout but does not
own the matrix data. Callers still have to pair it with a buffer, local-size
values, offsets, and descriptor/context state. In this series that distribution
role is now represented by the frozen Parallel_Blkcyclic handle used inside
Matrix2d. The important interface change is that the matrix composes that
handle with its data: callers pass one matrix value, then query the layout from
it when needed.

Parallel_Orbitals goes further and is intentionally an LCAO coordination
object. It mixes the Hamiltonian layout with wavefunction/MO layouts, band
sizes, atom traces, orbital index maps, and mutable bookkeeping. That is too
much state for a generic matrix routine and makes an omnibus object the
implicit context for otherwise independent math. Matrix2d has one job:
represent matrix data and its layout. It can be constructed, copied, passed,
and tested without an LCAO basis, atom table, band distribution, or
GlobalV/PARAM dependency.

This is a separation of responsibilities, not a claim that every
Parallel_Orbitals responsibility has disappeared. The PR does not introduce
a replacement omnibus object.

Scope and current coverage

This is a foundation-only feature PR. It adds:

  • owned host and frozen block-cyclic storage through Matrix2d<T>;
  • a non-owning Matrix2dView<T> for interop and explicitly named _inplace
    primitives whose mutation contract is documented;
  • elementwise arithmetic, conjugate/transpose/dagger, matrix multiplication,
    reductions, diagonal extraction, gather/scatter, and layout queries;
  • NumPy-style value-returning and output-parameter overloads for solve,
    matmul, inv, axpby, and scale, plus eye, transpose, and dagger;
  • LAPACK/ScaLAPACK-backed solve and inverse operations for double and
    std::complex<double>;
  • serial, 2-rank, and 4-rank unit coverage for layout, ownership, lifetime,
    padding, collectives, input immutability, context preservation, and linear
    algebra with real and complex matrices.

Not in this PR:

  • no production call sites are migrated to Matrix2d;
  • no Parallel_Orbitals or block-cyclic layout object is removed or replaced;
  • no INPUT, output, numerical workflow, or other user-facing behavior changes;
  • no claim that all existing LCAO matrix code already follows the new pattern.

The public header documentation and this Quick start are the documentation update
for the new interface. No separate user manual page is added because this PR has
no production callers or user-facing workflow yet.

Verification

Local commands and fresh results for commit 664c8df94b051b71271941572f0edb08e218a14c:

cmake --build build-matrix2d-serial --target MODULE_BASE_matrix2d MODULE_BASE_matrix2d_linalg -j 2
ctest --test-dir build-matrix2d-serial --output-on-failure -R '^MODULE_BASE_matrix2d(_linalg)?$'
# 2/2 tests passed

cmake --build build-matrix2d-mpi --target MODULE_BASE_matrix2d MODULE_BASE_matrix2d_linalg -j 2
LD_LIBRARY_PATH=/opt/apps/scalapack-2.2.2/lib:/opt/apps/openblas-0.3.29/lib:/opt/apps/fftw-3.3.10/lib ctest --test-dir build-matrix2d-mpi --output-on-failure -R '^MODULE_BASE_matrix2d'
# 6/6 tests passed, including 1-, 2-, and 4-rank Matrix2d and Matrix2d linalg runs

cmake --build build-matrix2d-cxx11 --target base -j 2
cmake --build build-matrix2d-mpi-cxx11 --target base -j 2
# both serial and MPI C++11 base builds passed

g++ -std=c++11 -I. -Isource -x c++ -fsyntax-only -
# standalone C++11 overload-resolution check passed: solve(A,B) -> Matrix2d<T>,
# solve(A,B,X) -> void, and Matrix2dView arguments require solve_inplace

git diff --check
# passed

python3 tools/03_code_analysis/code_quality_score.py source/source_base/matrix2d_linalg.cpp source/source_base/matrix2d_linalg.h source/source_base/unittests/test_matrix2d_linalg.cpp
# 3/3 files passed; average score 88.7 (94, 93, 79)

python3 tools/03_code_analysis/agent_governance_check.py --staged
# no blockers; its documentation-sync warning is addressed by the header docs,
# Scope section, and Quick start update in this PR body

The local pre-commit executable is not installed, so the underlying Agent
Governance checker was run directly. The GitHub checks remain the authoritative
current verification result for this revision.

Tests specifically verify value-returning and output-parameter forms, unchanged
inputs, output aliasing, real and complex scalars, host and serial layouts, and
2-/4-rank distributions with preserved process grids, block sizes, and BLACS
contexts. Return values are by value in C++11; no API returns Matrix2d<T>&&.

Retain borrowed BLACS contexts for derived distributed matrices, reject the unused raw-descriptor view path, and route serial frozen layouts through the local linear algebra backend. Add lifetime and serial-layout coverage.
Name borrowed BLACS-context factories separately from communicator-owned factories because Intel MPI defines MPI_Comm as int. Update Matrix2d and tests to use the explicit borrowed-distribution API.

@ABACUS-PR-BOT ABACUS-PR-BOT left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The factory rename resolves the integer-communicator overload collision in source. Please address the three implementation issues below.

Static source review of 25fec99: git diff --check passed. No builds or tests were run, and CI was not verified.

Comment thread source/source_base/matrix2d.cpp Resolved
Comment thread source/source_base/matrix2d.h Resolved
Comment thread source/source_base/matrix2d.h Resolved
Comment thread source/source_base/matrix2d_linalg.h Resolved
@mohanchen mohanchen added the Refactor Refactor ABACUS codes label Nov 17, 2026
Address the blocking findings: preserve serial view layout, support tall/skinny matrix storage, and remove INT_MIN negation UB. Also address non-blocking findings: clarify API contracts, use named locals in conditional call arguments, make matmul tests fail on internal errors instead of passing falsely, and document view overlap constraints.

@ABACUS-PR-BOT ABACUS-PR-BOT left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The three implementation issues from my previous review are addressed in 5db95a7. One earlier cleanup remains, noted in its original thread; the additional nonblocking comment concerns an existing gather error path.

Static source review only; the full-PR and incremental git diff --check checks passed. No builds or tests were run, and CI was not verified.

const MPI_Comm comm)
{
const std::vector<unsigned char> local_payload = make_local_payload(matrix);
const int local_count = checked_mpi_count(local_payload.size());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: Please agree across ranks on oversized payloads before throwing here, including the equivalent path in gather_on_root(). With enough memory for packing, a 32769 x 8192 double matrix on a 2 x 1 grid with block size 32768 exceeds INT_MAX on only one rank. That rank throws instead of joining the count-exchange collective, so the peer may remain blocked if the caller catches the exception instead of aborting the job.

@kirk0830 kirk0830 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR is made by the agentic programmer since the workload is quite high for this refactor task. I also review the PR.
Presently, I have only reviewed parts of the whole PR, comments are left inline, waiting for the agent to fix and reply.

const std::shared_ptr<const Parallel_Blkcyclic> distrib
= matrix.distribution();
std::vector<int> metadata;
metadata.reserve(LOCAL_METADATA_SIZE + matrix.nrloc()

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these syntax looks misleading. Create the memory space for std::vector at first, then do the element assignment would be more straightforward and still insist the concept of avoiding memory fragments and performance issue by the push-back

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed this helper to allocate the exact-sized metadata vector first and fill it by index in fbaf69833. The single-allocation behavior is preserved without mixing reserve and push_back, and touched vectors with known final sizes follow the same pattern.

}

template <typename T>
std::vector<unsigned char> make_local_matrix_buffer(const Matrix2d<T>& matrix)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we are already in the context of matrix, no need to mention the matrix explicitly again. make_local_buffer, even make_locbuf would be clear enough

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed this to make_local_buffer and updated all call sites in fbaf69833. The enclosing matrix context already makes the buffer kind clear.

{
const std::vector<int> metadata = make_local_metadata(matrix);
const std::size_t nmeta = metadata.size();
const std::size_t nmeta_bytes = nmeta * sizeof(int);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nbytes_meta?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed nmeta_bytes to nbytes_meta in fbaf69833, so the n prefix denotes a count and the unit follows it consistently.

const std::vector<int> metadata = make_local_metadata(matrix);
const std::size_t nmeta = metadata.size();
const std::size_t nmeta_bytes = nmeta * sizeof(int);
const std::size_t data_elements = static_cast<std::size_t>(matrix.nrloc())

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the size of data, not the element. element is a too high level concept here

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed data_elements to ndata and documented it as the number of stored T values, explicitly distinct from a byte count (fbaf69833).

const std::size_t nmeta_bytes = nmeta * sizeof(int);
const std::size_t data_elements = static_cast<std::size_t>(matrix.nrloc())
* static_cast<std::size_t>(matrix.ncloc());
const std::size_t data_bytes = data_elements * sizeof(T);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

then the nbyte of data from the size

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The data byte count is now nbytes_data = ndata * sizeof(T) in fbaf69833, making the unit transition explicit at the definition.

const Matrix2d<T>& matrix,
const MPI_Comm comm)
{
const std::vector<unsigned char> local_buffer

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

locbuf?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed the serialized local payload to locbuf, with recvbuf/rxbuf for receive storage, in fbaf69833. This keeps short local names while functions and types retain descriptive names.

Comment thread source/source_base/matrix2d.cpp Resolved
Comment on lines +24 to +27
int mpi_count(const std::size_t nbytes)
{
return static_cast<int>(nbytes);
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the function has its name mismatching its behavior. Only a casting from size_t to int, why it is named the mpi_count?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Merged validation and conversion into checked_mpi_count(std::size_t), which checks the native int limit and then narrows, in 0ac210ae3. Collective and reduction code now share this helper.

Comment on lines +29 to +44
std::vector<int> make_byte_displs(const std::vector<int>& nbytes)
{
std::vector<int> displs(nbytes.size(), 0);
int offset = 0;
for (std::size_t ip = 0; ip < nbytes.size(); ++ip)
{
displs[ip] = offset;
if (nbytes[ip] > std::numeric_limits<int>::max() - offset)
{
throw std::invalid_argument(
"Matrix2d collective matrix buffer size overflow");
}
offset += nbytes[ip];
}
return displs;
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can a scan with the std::accumulate solve the same problem? this will make the codes lighter. but, the function name is not satisfying. make_byte_displs but what actually does is a kind of accumulation. Consider a better name, such as make_byte_offsets instead of the displacement

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed this to make_byte_offsets and kept the explicit scan in 0ac210ae3. std::accumulate returns only a total, while std::partial_sum would still require a widened accumulator and a checked conversion before every MPI count.

Comment on lines +46 to +62
std::vector<int> allgather_nbytes(const int nbytes_local, const MPI_Comm comm)
{
const int nproc = Parallel_Common::comm_size(comm);
const int nbytes_int = static_cast<int>(sizeof(int));
std::vector<int> recvcounts(static_cast<std::size_t>(nproc), nbytes_int);
const std::vector<int> rdispls
= make_byte_displs(recvcounts);
std::vector<int> nbytes(static_cast<std::size_t>(nproc), 0);

Parallel_Common::allgatherv_bytes(&nbytes_local,
nbytes_int,
nbytes.data(),
recvcounts.data(),
rdispls.data(),
comm);
return nbytes;
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

very confusing: is this function really needed? don't any the parallelization mechanism have this support? tuning and moving with respect to the byte is quite dangerous and confusing

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept the two-phase exchange because Allgatherv requires receive counts and displacements before payload transfer. The first phase now reuses the existing Parallel::allgather_int through ParaWorld, and the payload phase uses allgatherv_bytes; no MPI routine is called directly (0ac210ae3).

@mohanchen
mohanchen requested a review from MrLi000001 November 20, 2026 03:36

@kirk0830 kirk0830 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have made my second review, this is also the first thorough review on the whole PR. The naming of variables/functions/namespaces are not quite satisfying, which would be risks for future devel. I will fix them soon.

= make_byte_displs(metacounts);
const int metadata_total_bytes
= metadispls.back() + metacounts.back();
const int nbytes_int = static_cast<int>(sizeof(int));

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems this amount is always used in this file. Considering a const int W_INT = static_cast(sizeof(int)); at the head of this cpp file, which might be better.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Promoted the repeated width to a file-level constexpr int W_INT = sizeof(int) in both the collective and reduction implementations (fbaf69833).

Comment thread source/source_base/matrix2d.cpp Resolved
Comment thread source/source_base/matrix2d.h Resolved
Comment thread source/source_base/matrix2d.h Resolved
Comment thread source/source_base/matrix2d.h Outdated
}

template <typename U>
void assert_compatible_layout(const NDArray<U, 2>& other) const

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why its implementation is not placed in the cpp file?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved the non-template assert_compatible_layout implementation into matrix2d.cpp in 0ac210ae3. The storage initializer remains in the class definition because the templated constructors instantiate it for all supported scalar types.

@@ -0,0 +1,129 @@
#ifndef ABACUS_SOURCE_SOURCE_BASE_MATRIX2D_VIEW_H

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no leading documentations explaing about the design, purpose, usage of the implementation in this file, bad

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added file-level Doxygen to matrix2d_view.h in fbaf69833, covering non-owning storage, row-major host versus column-major distributed addressing, distribution lifetime, and assert() bounds behavior.

std::shared_ptr<const Parallel_Blkcyclic> distrib_;
};

#endif

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if this is the interface exposing to the external caller/user, make a complete documentation both inline and before any public functions

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documented the public view constructors and accessors in fbaf69833, including ownership, layout, leading dimension, distribution lifetime, and non-throwing bounds contract.

}

private:
T* data_;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cannot the std::weak_ptr of std::vector satisfy your need?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I kept T* plus a shared distribution handle because views must also wrap external buffers and future subviews; weak_ptr<vector<T>> would restrict storage origins and still would not guarantee that individual elements remain alive. The lifetime contract is now explicit in the header (fbaf69833).

}
} // namespace

void inv(Matrix2dView<double> matrix)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this function twist the matrix inversion to the linear problem solving? I mean, converting the inversion to the AX=I equation solving? This is the twist of semantics, I think that is why the numpy, scipy and pytorch they still provide such an API. User should know to always use the inversion of matrix with much are on it own rather than delegating such a numerical programming sense by us

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I verified that this path uses P?GETRF + P?GETRI, so it retains explicit inversion rather than rewriting the API as AX = I. Added the same public @warning that prefers solve() unless the inverse itself is required (3bf1d7f7f).

return static_cast<int>(value);
}

int queried_workspace_size(const std::complex<double>& value)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use ws to make consistent with the naming of blas/lapack

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed the ScaLAPACK workspaces to ws, iws, lws, and liws in fbaf69833, matching BLAS/LAPACK terminology while keeping the descriptive query helper name.

@ABACUS-PR-BOT ABACUS-PR-BOT left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current update needs __MPI retained on both Matrix2d test targets and wider or scaled intermediates for float norms. The additional API comment narrows the axpby overlap contract.

Static source review of fbbcadb540ee3baccbaf4f7a3a4040b6aa0e7af4, including the contributor delta, merge resolution, affected callers and build/test registration; no build, runtime test or numerical probe was run.

AddTest(
TARGET MODULE_BASE_matrix2d
LIBS parameter base device container
SOURCES test_matrix2d.cpp

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With ENABLE_MPI=ON, this directory disables __MPI, and neither Matrix2d target opts back in. That compiles out their distributed cases and MPI_Init, while linking base built with a different Parallel_Blkcyclic layout; the 2/4-rank CTest entries therefore do not validate the MPI implementation. Please add KEEP_FEATURE_DEFINITIONS __MPI to both AddTest calls and rerun the focused MPI tests.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both Matrix2d targets now retain __MPI, and the configure-time guard checks their retained feature property. This addresses the source mismatch described here. I checked the CMake trace statically; no configure, build or MPI tests were run.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. This was fixed in 5085c5811 by adding KEEP_FEATURE_DEFINITIONS __MPI to both Matrix2d test targets, together with a configure-time assertion. On a clean ENABLE_MPI=ON build, all 6 focused CTest entries passed; the 2-rank and 4-rank runs each exercised the distributed cases with Matrix2d 30/30 and linalg 11/11 passing.

real_type<T> abs2(const T& value)
{
const real_type<T> real_value = static_cast<real_type<T>>(value);
return real_value * real_value;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For float and complex<float>, real_type<T> also makes the intermediate squares single precision. A 1x1 matrix containing 1e20f now overflows before sqrt, and 1e-30f underflows to zero, although both Frobenius norms are representable; the previous double intermediates handled these cases. Please keep wider intermediates or use scaled sum-of-squares, then cast the final result to real_type<T> and add large/small float regressions.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this was a real precision bug. Fixed in 5ebd75f65: the Frobenius-norm square accumulation, max-abs magnitude calculation, OpenMP reductions, and MPI reductions now use double intermediates for float, double, complex, and integer inputs. The public result is cast back to real_type<T> only after the reduction completes. I added regressions in ReductionsUseTheMatrixRealType for 1e20f and 1e-30f, including the corresponding complex<float> values. Clean serial and MPI 2/4-rank Matrix2d tests pass.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reported float and complex range cases are addressed in 5ebd75f65. A remaining issue in this PR predates this fix: with binary64 intermediates, a 1x1 double matrix containing 1e200 still overflows on squaring and 1e-200 underflows to zero, although both norms are representable; complex<double> with zero imaginary part has the same issue. Please use scaled sum-of-squares and add the corresponding double/complex regressions.

Comment thread source/source_base/matrix2d_linalg.h Outdated
*
* All views must have the same global shape and compatible host or distributed
* layouts. The result may overlap either input because each element is read
* before it is written.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: Please restrict the overlap guarantee to views with identical element mapping. Shifted views such as left=buffer and result=buffer+1 pass the shape checks, but an early write overwrites a later input (and the OpenMP loop can race). Document other overlap as unsupported and add an exact in-place alias test.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in 5ebd75f65. The Doxygen contract now states that matmul supports no overlap, while axpby supports only views with the same logical element mapping, including an exact in-place alias; shifted and partial overlap are explicitly unsupported. I added exact in-place axpby(result=A, ..., left=A, ...) coverage to HostViewMatmulAndAxpby. It passes in the clean suites and separately with OMP_NUM_THREADS=4.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The contract in 5ebd75f65 now permits only identical element mapping and explicitly excludes shifted/partial overlap. The new exact in-place axpby test computes its expected result from a saved pre-operation copy. This addresses the documented aliasing issue.

@ABACUS-PR-BOT ABACUS-PR-BOT left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The float-range, alias-contract and named-offset fixes are addressed in source. The remaining double-norm range issue is tracked in the original norm thread.

Non-blocking: Please add the exact configure/build/test commands, relevant options and observed outcomes to the Verification section. Your replies report serial, MPI 2-/4-rank and OMP_NUM_THREADS=4 results, but the commands needed to reproduce those runs are not recorded.

Static review of 5ebd75f65; no builds or tests were run, and CI was not verified.

template <typename T>
void check_float_reduction_range(const T& value, const float expected)
{
Matrix2d<T> matrix(1, 1);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: Please exercise the float and complex range cases with an active distribution too. This helper always constructs a host matrix, so even the 2-/4-rank launches skip the collective path whose norm accumulator changes from float to double. A distributed 1x1 case would also cover ranks with no local entries.

@ABACUS-PR-BOT ABACUS-PR-BOT left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new owning operations produce incompatible serial-frozen results in the case below. Two non-blocking comments cover the test and public type contract.

Non-blocking: the Verification section now records build/test commands and reported outcomes. Please also include the configure commands or relevant cache options for the serial, MPI and C++11 build directories so those runs can be reproduced.

Static incremental review of 664c8df94b051b71271941572f0edb08e218a14c; no builds or runtime tests were run, and CI was not verified.

}
if (!source.is_active())
{
return Matrix2d<T>(make_frozen_distribution(nrglb, ncglb));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Please reuse the source distribution handle when the result shape is unchanged, including this serial-frozen branch. With a matrix constructed using make_frozen_distribution(2, 2), auto r = axpby(1.0, a, 0.0, a) gets a different handle, so r += a and r.dot(a) throw despite matching dimensions and indexing. Move the same-shape reuse check before this branch and cover composition of serial-frozen results with their inputs.

const int nrblk)
{
const Matrix2d<T> expected = matrix2d_linalg::inv(host_matrix);
const Matrix2d<T> host_matrix_original = host_matrix;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: capture host_matrix_original before calling inv(host_matrix). The immediate equality check currently copies and compares the already-processed input, so it cannot detect mutation by that call. Other host tests have valid before-snapshots; this particular assertion should do the same.

template <typename T>
Matrix2d<T> eye(const int n);

/** @brief Return the non-conjugate transpose of `matrix`. */

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: document or constrain the scalar types supported by transpose, dagger, and scale. Their declarations accept other Matrix2d types such as float, but the implementation exports only double and std::complex<double> instantiations, so other specializations fail at link time. Matching the explicit type notes on the other linalg functions would make this limit clear.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Refactor Refactor ABACUS codes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants